package com.zhong.ui;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class TabActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private String[] titles = {"aaa","bbb","ccc"};
    private List<Fragment> fragments = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);

        mTabLayout = findViewById(R.id.tab_layout);
        mViewPager = findViewById(R.id.view_pager);


        for(int i = 0; i < titles.length; i ++){
            fragments.add(TabFragment.newInstance(TabActivity.this, titles[i]));

            LinearLayout line = new LinearLayout(TabActivity.this);
            line.setOrientation(LinearLayout.VERTICAL);
            line.setGravity(Gravity.CENTER_VERTICAL);
            ImageView image = new ImageView(TabActivity.this);
            image.setBackgroundResource(R.mipmap.ic_launcher);
            TextView textView = new TextView(TabActivity.this);
            textView.setText(titles[i]);
            line.addView(image);
            line.addView(textView);

            mTabLayout.addTab(mTabLayout.newTab().setCustomView(line));
        }


        mTabLayout.setTabMode(TabLayout.MODE_FIXED);   //设置Tab为可滑动的
        mTabLayout.setTabTextColors(Color.RED, Color.GREEN); //设置字体颜色
        mViewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        mTabLayout.setupWithViewPager(mViewPager); //绑定ViewPager 注意必须在setAdapter之后


        mViewPager.addOnPageChangeListener(new
                TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
        mTabLayout.setOnTabSelectedListener(new
                TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    }

    class MyViewPagerAdapter extends FragmentPagerAdapter {


        public MyViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

}
